package zzj.campus_book_sharing_platform.test;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

@RequiredArgsConstructor
@Slf4j
@Service
public class FileServiceImpl implements IFileService {

    @Override
    public void word2Pdf(MultipartFile file, HttpServletResponse response) {

        String fileName = file.getOriginalFilename();
        Path wordFilePath = Paths.get(Constants.filePath , File.separator , UUID.randomUUID().toString());
        try {
            File wordFile = creatFile(file.getInputStream(), String.valueOf(wordFilePath), fileName);
            fileName = wordFile.getName().split("\\.")[0] + ".pdf";
            File PdfFile = creatFile(new ByteArrayInputStream(new byte[0]), wordFile.getParent(), fileName);
            FileUtil.wordToPdf(wordFile, PdfFile);
            getResponse(response, fileName,PdfFile);
        } catch (Exception e) {
            log.error("word转换pdf失败！" + e.getMessage() + " 堆栈信息：" + Arrays.toString(e.getStackTrace()));
        }
    }

    /**
     * 设置响应内容
     *
     * @param response 响应
     * @param fileName 文件名
     * @return 响应
     */
    public HttpServletResponse getResponse(HttpServletResponse response, String fileName,File PdfFile) {
        response.setContentType("application/pdf");
        response.setHeader("Cache-control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setCharacterEncoding("UTF-8");
        fileName = fileName.split("\\.")[0];
        // 设置响应头部，以及文件名进行中文防止乱码转码操作
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".pdf", "UTF-8"));
            // 将 PDF 文件内容写入响应输出流
            FileInputStream fis = null;
            OutputStream fos = null;
            try {
                fos = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead;
                fis = new FileInputStream(PdfFile);
                while ((bytesRead = fis.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                fos.flush();
            } catch (IOException e) {
                log.error(e.getMessage() + "堆栈信息：" + Arrays.toString(e.getStackTrace()));
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        log.error(e.getMessage() + "堆栈信息：" + Arrays.toString(e.getStackTrace()));
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        log.error(e.getMessage() + "堆栈信息：" + Arrays.toString(e.getStackTrace()));
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage() + "堆栈信息：" + Arrays.toString(e.getStackTrace()));
        }
        return response;
    }

    /**
     * 创建缓存文件目录
     */
    public String creatDir(String filePath) {
        File fileDir = new File(filePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        return fileDir.getPath();
    }

    /**
     * 保存缓存文件
     *
     * @param inputStream 文件流
     * @param fileName    文件路径
     * @return 生成文件
     */
    public File creatFile(InputStream inputStream, String filePath, String fileName) throws IOException {
        String Path = creatDir(filePath);
        File file = new File(Path, fileName);
        OutputStream outputStream = null;
        try {
            outputStream = Files.newOutputStream(file.toPath());
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage() + "堆栈信息：" + Arrays.toString(e.getStackTrace()));
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage() + "堆栈信息：" + Arrays.toString(e.getStackTrace()));
                }
            }
        }
        return file;
    }
}
